package controller

import (
	"SE/Response"
	"SE/dao"
	"SE/global"
	"SE/model"
	"SE/service"
	"SE/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt" // 用于密码加密
	"net/http"
	"strconv"
)

type PasswordLoginForm struct {
	Mobile    string `form:"mobile" json:"mobile" binding:"required"` //手机号码格式有规范可寻， 自定义validator
	PassWord  string `form:"password" json:"password" binding:"required,min=3,max=20"`
	Captcha   string `form:"captcha" json:"captcha" binding:"required,min=5,max=5"` // 验证码
	CaptchaId string `form:"captcha_id" json:"captcha_id" binding:"required"`       // 验证码id
}

type MeLogin struct {
	Captcha   string `form:"captcha" json:"captcha" binding:"required,min=5,max=5"`
	CaptchaId string `form:"captcha_id" json:"captcha_id" binding:"required"`
}

// UserController 结构体
type UserController struct {
	userService service.UserService
}

// NewUserController 构造函数
func NewUserController(userService service.UserService) *UserController {
	return &UserController{userService: userService}
}

// Register 处理用户注册请求
func (uc *UserController) Register(c *gin.Context) {
	//LoginForm := MeLogin{}
	//
	//if err := c.ShouldBind(&LoginForm); err != nil {
	//	// 统一处理异常
	//	utils.HandleValidatorError(c, err)
	//	return
	//}
	//if !store.Verify(LoginForm.CaptchaId, LoginForm.Captcha, true) {
	//	Response.Err(c, 400, "验证码错误", "")
	//	return
	//}

	var user model.User
	// 解析请求体中的JSON数据到user结构体
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
		return
	}

	// 验证用户输入，确保电话和密码不为空
	if user.Mobile == "" || user.Password == "" {
		Response.Err(c, 400, "手机号或密码为空", nil)
		return
	}

	// 检查用户名和电话是否已存在
	if uc.userService.UserExists(user.UserName, user.Mobile) {
		Response.Err(c, 400, "用户名或电话已存在", nil)
		return
	}

	// 加密密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		Response.Err(c, 400, "密码加密失败", err)
		return
	}
	user.Password = string(hashedPassword)

	// 创建用户
	if err := uc.userService.CreateUser(&user); err != nil {
		Response.Err(c, 400, "用户注册失败", err)
		return
	}

	// 返回成功响应
	Response.Success(c, 200, "success", user)
}

// Login 登录
func Login(c *gin.Context) {
	PasswordLoginForm := PasswordLoginForm{}

	if err := c.ShouldBind(&PasswordLoginForm); err != nil {
		// 统一处理异常
		utils.HandleValidatorError(c, err)
		return
	}
	if !store.Verify(PasswordLoginForm.CaptchaId, PasswordLoginForm.Captcha, true) {
		Response.Err(c, 400, "验证码错误", "")
		return
	}
	// 查询数据库是否注册该用户
	user, ok := dao.FindUserInfo(PasswordLoginForm.Mobile, PasswordLoginForm.PassWord)
	if !ok {
		Response.Err(c, 400, "没有注册", "")
		return
	}
	token := utils.CreateToken(c, int(user.ID), user.UserName, 1)
	userinfoMap := HandleUserModelToMap(user)
	userinfoMap["token"] = token
	Response.Success(c, 200, "success", userinfoMap)
}

// HandleUserModelToMap 模型转map
func HandleUserModelToMap(user *model.User) map[string]interface{} {
	userItemMap := map[string]interface{}{
		"id":      user.ID,
		"address": user.Address,
		"mobile":  user.Mobile,
	}
	return userItemMap
}

func MLogin(c *gin.Context) {

	var m model.Manager
	m.Code, _ = strconv.Atoi(c.Query("code"))
	m.Mobile = c.Query("mobile")
	if m.Mobile == "" || m.Code == 0 {
		Response.Err(c, 400, "手机号或工号为空", "")
		return
	}
	if !dao.FindUserInfoByMobile(m.Mobile, m.Code) {
		Response.Err(c, 400, "该用户不存在", "")
		return
	}
	Response.Success(c, 200, "success", "登陆成功")

}
func SearchHistory(c *gin.Context) {
	//var req struct {
	//	Uid string `json:"uid" binding:"required"`
	//}
	//
	//c.ShouldBindJSON(&req) //; err != nil {
	////	Response.Err(c, 400, "无效的请求参数", err)
	////	return
	////}
	uid := c.Query("uid")

	var Cp []model.CarP
	if err := global.DB.Where("uid = ?", uid).Find(&Cp).Error; err != nil {
		Response.Err(c, 400, "查询失败", err)
		return
	}

	Response.Success(c, 200, "success", Cp)
}

func MPhone(c *gin.Context) {
	code := c.Query("code")
	//if err != nil {
	//	Response.Err(c, 400, "参数错误", err)
	//	return
	//}
	fmt.Println("code:", code)
	var m model.Manager
	global.DB.Where("code = ?", code).Find(&m)
	if m.Mobile == "" {
		Response.Err(c, 400, "该用户不存在", "")
		return
	}
	Response.Success(c, 200, "success", m)
}
